package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    AddressBookService addressBookService;
   //保存地址方法
    @PostMapping
    public R addRess(@RequestBody AddressBook addressBook){
        //少参数需要set进去
        addressBook.setUserId(BaseContext.getCurrentId());
        //保存地址需要userId
        addressBookService.save(addressBook);
        return R.success("保存地址成功");
    }
    //展示用户的全部地址
    @GetMapping("/list")
    public R getAll(){
        //展示登录人的地址根据用户id
        QueryWrapper<AddressBook> qw=new QueryWrapper<>();
        //根据地址id字段和保存在共享线程中的用户id字段进行条件过滤
        qw.lambda().eq(AddressBook::getUserId, BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(qw);
       return R.success(list);

    }
    //修改地址状态
    @PutMapping("/default")
    public R addDefault(@RequestBody AddressBook addressBook){
        UpdateWrapper<AddressBook> qw=new UpdateWrapper<>();
        //这里要从全局线程中拿到对象因为前端没有 修改该用户下的所有路径
      qw.lambda().eq(AddressBook::getUserId, BaseContext.getCurrentId());
        // 把这个登录用户的所有地址默认值设置为0
      qw.lambda().set(AddressBook::getIsDefault,0);
      //接下来修改数据库中的数据 修改为0
        addressBookService.update(qw);
        //根据具体传过来的来修改
        UpdateWrapper<AddressBook> qw2=new UpdateWrapper<>();
        qw2.lambda().set(AddressBook::getIsDefault,1);
        qw2.lambda().eq(AddressBook::getId,addressBook.getId());
        addressBookService.update(qw2);
        return R.success("修改成功");
    }
    //回显数据
    @GetMapping("/{id}")
    public R getRess(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return R.success(addressBook);
    }
    //删除地址
    @DeleteMapping
    public R deleteRess(@RequestParam List<Long> ids ){
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }
    //修改地址
    @PutMapping
    public R updateRess(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
    //设置默认地址
    @GetMapping("/default")
    public R getList(){
        QueryWrapper<AddressBook> qw=new QueryWrapper<>();
        Long userId = BaseContext.getCurrentId();
        qw.lambda().eq(AddressBook::getUserId,userId);
        qw.lambda().eq(AddressBook::getIsDefault,1);
        AddressBook one = addressBookService.getOne(qw);
        return R.success(one);
    }
}
